#include <bits/stdc++.h>
#ifndef DEBUG
#define debug
#endif
using namespace std;
using i64 = int64_t;


int main() {
  cin.tie(0)->sync_with_stdio(0);
  int n;
  cin >> n;
  vector<vector<int>> trans(26, vector<int>(26));
  while (n --) {
    string s;
    cin >> s;
    trans[(s[1] - 'A')][(s[2] - 'A')] |= 1 << (s[0] - 'A');
  }
  int Q;
  cin >> Q;
  while (Q--) {
    string s;
    cin >> s;
    int n = s.size();
    vector<vector<int>> dp(n, vector<int>(n));
    for (int l = n - 1; l >= 0; l --) {
      dp[l][l] = 1 << (s[l] - 'a');
      for (int r = l + 1; r < n; r ++) {
        for (int k = l; k < r; k ++) {
          for (int i = 0; i < 26; i ++) {
            if ((dp[l][k] >> i & 1) == 0) continue;
            for (int j = 0; j < 26; j ++) {
              if ((dp[k + 1][r] >> j & 1) == 0) continue;
              dp[l][r] |= trans[i][j];
            }
          }
        }
      }
    }
    vector<int> dp2(n + 1, INT_MAX / 2);
    dp2[0] = 0;
    for (int i = 1; i <= n; i ++) {
      for (int j = 1; j <= i; j ++) {
        if ((dp[j - 1][i - 1] >> ('S' - 'A') & 1) == 0) continue;
        dp2[i] = min(dp2[i], dp2[j - 1] + 1);
      }
    }
    if (dp2[n] == INT_MAX / 2) {
      cout << "NIE" << endl;
    } else {
      cout << dp2[n] << endl;
    }
  }
}